//
//  UIImageView+OMTImagePicker.m
//  OMTImagePicker
//
//  Created by yizhaorong on 2017/11/15.
//

#import "UIImageView+OMTAsset.h"
#import "OMTAlbumManager.h"
#import <objc/runtime.h>

@implementation UIImageView (OMTAsset)

- (void)setOmt_asset:(OMTAsset *)omt_asset {
    objc_setAssociatedObject(self, @selector(omt_asset), omt_asset, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (OMTAsset *)omt_asset {
    return objc_getAssociatedObject(self, @selector(omt_asset));
}

- (void)setOmt_album:(OMTAlbum *)omt_album {
    objc_setAssociatedObject(self, @selector(omt_album), omt_album, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (OMTAsset *)omt_album {
    return objc_getAssociatedObject(self, @selector(omt_album));
}

- (void)setRequestId:(NSInteger)requestId {
    objc_setAssociatedObject(self, @selector(requestId), @(requestId), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSInteger)requestId {
    id value = objc_getAssociatedObject(self, @selector(requestId));
    return [value integerValue];
}

- (void)omt_setImageWithAsset:(OMTAsset *)asset {
    [self omt_setImageWithAsset:asset placeholderImage:nil];
}

- (void)omt_setImageWithAsset:(OMTAsset *)asset placeholderImage:(UIImage *)placeholder {
    [self omt_setImageWithAsset:asset placeholderImage:placeholder completion:nil];
}

- (void)omt_setImageWithAsset:(OMTAsset *)asset placeholderImage:(UIImage *)placeholder completion:(void (^)(UIImage *image, OMTAsset *asset))completion {
    [self.omt_asset.albumManager cancelRequest:self.requestId];
    self.omt_asset = asset;
    self.image = placeholder;
    __weak typeof(self) weakSelf = self;
    self.requestId = [asset.albumManager defaultPhotoWithAsset:asset completion:^(UIImage *image, NSData *imageData, NSDictionary *info, BOOL isDegraded, OMTAsset *asset, BOOL finished) {
        typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (!finished) return;
        if (strongSelf.omt_asset != asset) return;
        omt_album_dispatch_async_on_main_queue(^{
            strongSelf.image = image;
            if (completion) completion(image, asset);
        });
    }];
    
}

- (void)omt_setImageWithAlbum:(OMTAlbum *)album {
    [self omt_setImageWithAlbum:album placeholderImage:nil];
}

- (void)omt_setImageWithAlbum:(OMTAlbum *)album placeholderImage:(UIImage *)placeholder {
    [self.omt_album.albumManager cancelRequest:self.requestId];
    self.omt_album = album;
    self.image = placeholder;
    __weak typeof(self) weakSelf = self;
    self.requestId = [album.albumManager coverWithAlbum:album completion:^(UIImage *image, OMTAlbum *album, BOOL finished) {
        typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (!finished) return;
        if (strongSelf.omt_album != album) return;
        omt_album_dispatch_async_on_main_queue(^{
            strongSelf.image = image;
        });
    }];
}

@end
